<?php
namespace core\modules;

use core\Func;

/**
 * 基础访问控制模块
 */
class AcManager
{
	static public $allACList=array();

	private $data=array();

  // 注册权限列表
	static function reg($key,$title,$desc=""){
		$key=trim($key);
		if (isset(static::$allACList[$key])){
      throw new Exception("AC key duplicate: ".$key);
    }
    static::$allMenus[$key]=array(
			"id"=>$key,
			"label"=>$title,
			"remark"=>$desc,
		);
	}
	function __construct(){
		if (empty(static::$allACList)){
			$this->init();
		}
  }

	function init(){
    $this->clean();
    $ac_conf=config("ac.");
		$ac_conf=$this->formatConfig($ac_conf);
		$ac_menu=config("menu.");
		$ac_menu=$this->formatConfig($ac_menu,true);

		static::$allACList=array_merge($ac_conf,$ac_menu);

  }
	// 获取树形列表
	function getTree(){
		return static::$allACList;
	}
	// 格式化ac配置
	function formatConfig($conf,$check_id=false,$check_type=[]){
		static $deep=0;
		$deep++;
		$result=[];
		if (is_array($conf)){
			foreach ($conf as $v) {
				if (!empty($check_type)){
					if (empty($v["type"])) continue;
					$check_types=Func::str2arr($check_type);
					if (!in_array($v["type"],$check_types)) continue;
				}
				$label=(empty($v["label"]))?(empty($v["title"])?"":$v["title"]):$v["label"];


				if (!empty($label)){
					$id = (empty($v["id"]))?(empty($v["ac"])?"_id_".$deep."_".md5($label):$v["ac"]):$v["id"];
					$id=rtrim($id,"/");
					$item=[
						"id"=>$id,
						"label"=>$label,
					];

					$children=(empty($v["children"]))?((empty($v["item"]))?"":$v["item"]):$v["children"];
					if (!empty($v["children"])){
						$item["children"]=$this->formatConfig($v["children"],$check_id,$check_type);
					}

					$add=true;
					if ($check_id){
						if ($item["id"]{0}=="_"){
							if (empty($item["children"])) $add=false;
						}
					}
					if ($add)	$result[]=$item;
				}

			}
		}
		$deep--;
		return $result;
	}
	// 获取名称，数组模式
	function getNameArr($keys,$return_str=false){

		$keys=Func::json2arr($keys);
		$result=[];
		foreach ($keys as $v) {
			$result[]=$this->getName($v);
		}
		if ($return_str) $result=Func::arr2str($result,", ");
		return $result;
	}
	// 获取名称
	function getName($key,$list=[]){
		$result="";
		$list=(empty($list))?static::$allACList:$list;
		foreach ($list as $v) {
			if ($v["id"]==$key){
				$result=$v["label"];
				break;
			}
			if (!empty($v["children"])){
				$result=$this->getName($key,$v["children"]);
				if (!empty($result)){
					break;
				}
			}
		}

		return $result;
	}

	// 清理
	function clean(){
		static::$allACList=[];

	}


}
